/*******************************************************************************
 *
 *    The information contained herein is the exclusive property of
 *  Sunplus app Technology Co. Ltd. And shall not be distributed, reproduced,
 *  or disclosed in whole in part without prior written permission.
 *
 *           (C) COPYRIGHT 2008-2014  Sunplus app Technology Co. Ltd.
 *                            ALL RIGHTS RESERVED
 *
 *    The entire notice above must be reproduced on all authorized copies.
 *
 *******************************************************************************
 *
 * Description: C++ plugin for main.qml
 * Others:      None.
 * History:
 *   v1.0       Lijian<lijian@sunplusapp.com>
 *     1) Add xxx and xxx functions.
 *     2) fix some bug of function XXXX.
 *
 *   v0.1       Lijian<lijian@sunplusapp.com>
 *     1) created.
 *
 ******************************************************************************/
#include "SystemUtils.h"
#include <QProcess>
#include <qjson/parser.h>
#include <qjson/serializer.h>
#include <QFile>
#include <QCoreApplication>
#include <QDebug>
#ifndef _WIN32
#include <sys/inotify.h>
#include <QSocketNotifier>
#include <unistd.h>
#endif

SystemUtils::SystemUtils(QObject *parent) :
    QObject(parent)
{
    _bg = "bg.jpg";
    _bgList<<"0.jpg"<<"1.jpg"<<"2.jpg"<<"3.jpg"
             <<"4.jpg"<<"5.jpg"<<"6.jpg"<<"7.jpg";

    _iconPageListFilePath = "qml/sDesktop/iconPage.json";
    if(QFile::exists(QString("%1/%2").arg(QCoreApplication::applicationDirPath()).arg(_iconPageListFilePath)))
        _iconPageListFilePath = QString("%1/%2").arg(QCoreApplication::applicationDirPath()).arg(_iconPageListFilePath);
    else if(QFile::exists(QString("%1/../%2").arg(QCoreApplication::applicationDirPath()).arg(_iconPageListFilePath)))
        _iconPageListFilePath = QString("%1/../%2").arg(QCoreApplication::applicationDirPath()).arg(_iconPageListFilePath);
#ifndef _WIN32
    _inotify_fd = inotify_init();
    _watch_fd = inotify_add_watch(_inotify_fd, _iconPageListFilePath.toUtf8().constData(), IN_MODIFY);
    _inotify_nodifier = new QSocketNotifier(_inotify_fd, QSocketNotifier::Read, this);
    connect(_inotify_nodifier, SIGNAL(activated(int)), this, SLOT(onWatchTriggered()));
#endif
}

SystemUtils::~SystemUtils()
{
#ifndef _WIN32
    delete _inotify_nodifier;
    inotify_rm_watch(_inotify_fd, _watch_fd);
    ::close(_inotify_fd);
#endif
}

void SystemUtils::onWatchTriggered()
{
#ifndef _WIN32
    char buf[1024];
    ::read(_inotify_fd, buf, sizeof(buf));
    emit iconPageListsChanged();
#endif
}

QString SystemUtils::iconPageLists() const
{
    QString path = "qml/sDesktop/iconPage.json";
    if(QFile::exists(QString("%1/%2").arg(QCoreApplication::applicationDirPath()).arg(path)))
        path = QString("%1/%2").arg(QCoreApplication::applicationDirPath()).arg(path);
    else if(QFile::exists(QString("%1/../%2").arg(QCoreApplication::applicationDirPath()).arg(path)))
        path = QString("%1/../%2").arg(QCoreApplication::applicationDirPath()).arg(path);
    QFile f(path);
    if(!f.open(QFile::ReadOnly)) {
        qDebug()<<"failed to open iconPage.json";
        return "";
    }
    QByteArray d = f.readAll();
    f.close();
    return QString::fromUtf8(d.constData());
}

void SystemUtils::run(const QString &cmd, const QString &arg)
{
    QStringList args;
//    if(!arg.contains("\""))
//        args = arg.split(" ");
//    else
    {
        QString lastArg;
        bool flag = false;
        foreach(const QChar &ch, arg)
        {
            if(flag)
            {
                if(ch == '\"')
                {
                    args.append(lastArg);
                    lastArg.clear();
                }
                else
                    lastArg.append(ch);
            }
            else if(ch == '\"')
                flag = true;
            else if((ch == ' ') && (!lastArg.isEmpty()))
            {
                args.append(lastArg);
                lastArg.clear();
            }
            else
                lastArg.append(ch);
        }
        if(!lastArg.isEmpty())
            args.append(lastArg);
    }
    qDebug()<<"run"<<cmd<<args.count()<<args;
    QProcess::startDetached(cmd, args);
}
